﻿/**
文件上传类,包含预览功能
需要Flash Player 10

	<code>
		触发浏览窗口
		var fileUploader = new FileUpload();
		fileUploader.extensions = ["*.jpg;*.gif;*.png"];
		fileUploader.descriptions = ["Images"];
		fileUploader.maxsize = 1000000;
		//picUploadPath为后台上传文件地址
		fileUploader.filePath = Path.picUploadPath;
		fileUploader.browse();
		fileUploader.addEventListener(FileEvent.SELECTED, onFileSelected);
		fileUploader.addEventListener(FileEvent.PREVIEW_PROGRESS, onFilePreviewProgress);
		fileUploader.addEventListener(FileEvent.PREVIEW_COMPLETE, onFilePreview);
		fileUploader.addEventListener(FileEvent.UPLOAD,onFileUpload);
		function onFileSelected(e:FileEvent) {
			//取得上传文件随机名 可携带参数传递后台
			sndFileUploader.filePath = Path.sndUploadPath + "?sName=" + e.fileProperties;
			//sndFileUploader.filePath = Path.sndUploadPath;
		}
		function onFileUpload(e:FileEvent)	{
			trace("上传完成..");
			// TODO	: CompleteHandle..
		}
		触发上传
		fileUploader.upload();
	</code>
	
	@experience
	上传完成后无法取得返回数据
	@expand
	回收处理机制
	@
**/

package org.nickro.project.utils{
	import flash.display.Loader;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	
	import com.adobe.crypto.MD5;
	
	import flash.events.EventDispatcher;
	import flash.events.ProgressEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.HTTPStatusEvent;
	import flash.net.FileReference;
	import flash.net.FileFilter;
	
	import org.nickro.project.manager.PopUpManager;
	import org.nickro.project.events.FileEvent;
	import org.nickro.project.debug.Console;
	/**
	 * @includeExample	Example/FileUpload
	 * @playerVersion 10
	 */
	[Event(name = "selected", type = "app.events.FileEvent")]
	/**
	 * @includeExample Example/FileUpload
	 * @playerVersion 10
	 */
	[Event(name = "upload" , type = "app.events.FileEvent")]
	
	public class FileUpload extends EventDispatcher{
		public function FileUpload(){
			
		}
	
		private var filterfilterArray:Array = [];
		private var fr:FileReference;
		public function browse()
		{
			fr = new FileReference();
			fr.addEventListener(Event.SELECT, onSelect);
			if (extensions.length != extensions.length) {
				fr.cancel();
				throw new Error("文件类型与文件描述不对称.");
			}
			for (var i :int = 0; i < descriptions.length; i++) {
				filterfilterArray.push(new FileFilter(descriptions[i],extensions[i]));
			}
			fr.browse(filterfilterArray);
		}
		
		private function onSelect(e:Event):void
		{
			fr.removeEventListener(Event.SELECT, onSelect);
			
			if(fr.size > _maxsize){
				PopUpManager.popError("文件过大,请重新上传.");
				//fr.browse(filterfilterArray);
			}else {
				//随机数生成
				md5_filename = MD5.hash(fr.name + Math.round(Math.random() * 899) + 100);
				dispatchEvent(new FileEvent(FileEvent.SELECTED,{name:fr.name,md5_name:md5_filename}));
				//加载本地选择的文件,提供预览功能
				if (_isPreview) {
					fr.load();
					fr.addEventListener(ProgressEvent.PROGRESS, onFilePreviewProgress);
					function onFilePreviewProgress(e:ProgressEvent):void
					{
						var percent:int = int(e.bytesLoaded/e.bytesTotal * 100)
						dispatchEvent(new FileEvent(FileEvent.PREVIEW_PROGRESS, percent));
					}
					fr.addEventListener(Event.COMPLETE, onFilePreview);
					
					function onFilePreview(e:Event):void
					{
						fr.removeEventListener(ProgressEvent.PROGRESS, onFilePreviewProgress);
						fr.removeEventListener(Event.COMPLETE, onFilePreview);
						dispatchEvent(new FileEvent(FileEvent.PREVIEW_COMPLETE, e.target.data));
					}
				}
			}
		}
		
		public function upload():void
		{
			fr.upload(new URLRequest(_path));
			fr.addEventListener(Event.OPEN, onOpen);
			fr.addEventListener(ProgressEvent.PROGRESS,onProgress);
			fr.addEventListener(Event.COMPLETE,onComplete);
			fr.addEventListener(IOErrorEvent.IO_ERROR,onIO_Error);
			fr.addEventListener(HTTPStatusEvent.HTTP_STATUS,onHTTP_Status);
			fr.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurity_Error);
			function onOpen(e:Event):void
			{
				PopUpManager.popSendwait("上传中:0%");
			}
			function onProgress(e:ProgressEvent):void 
			{
				var percent:int = int((e.bytesLoaded / e.bytesTotal) * 100);
				PopUpManager.popSendwait("上传中:" + String(percent) + "%");
			}
			
			function onComplete(e:Event):void {
				Console.info("Debug [FileUpload] upload complete!");
				dispatchEvent(new FileEvent(FileEvent.UPLOAD));
				//PopUpManager.popSuccess("上传完成");
				
				//dispose();
				fr.removeEventListener(Event.OPEN, onOpen);
				fr.removeEventListener(ProgressEvent.PROGRESS,onProgress);
				fr.removeEventListener(Event.COMPLETE,onComplete);
				fr.removeEventListener(IOErrorEvent.IO_ERROR, onIO_Error);
				fr.removeEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTP_Status);
				fr.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurity_Error);
				
			}
			
			function onHTTP_Status(e:HTTPStatusEvent):void {
				fr.cancel();
				Console.info("Debug [FileUpload] HTTP Status :: " + e.status);
				PopUpManager.popError("FileUpload :: 网络出错!" + e.status);
			}
			
			function onIO_Error(e:Event):void {
				fr.cancel();
				Console.error("Debug [FileUpload] IO Error + " + String(e));
				PopUpManager.popError("FileUpload :: I/O错误" + String(e));
			}
			
			function onSecurity_Error(e:SecurityError):void 
			{
				fr.cancel();
				Console.error("Debug [FileUpload] Security Error " + String(e));
				PopUpManager.popError("没有上传权限!");
			}
		}
		/**
		 * @expand
		 */
		public function dispose():void
		{
			
		}
		
		
		//最大文件大小  //bit
		private var _maxsize:Number = 10 * 1024 * 1024;
		public function set maxsize(value:Number):void { _maxsize = value; };
		public function get maxsize():Number { return maxsize; };
		//文件描述 可以指定多个描述
		private var _descriptions:Array = ["Images"];
		public function get descriptions():Array { return _descriptions; };
		public function set descriptions(value:Array):void { _descriptions = value; };
		//文件类型	可以指定多个类型
		private var _extensions:Array = ["*.jpg;*.gif;*.png"];
		public function set extensions(value:Array):void { _extensions = value; };
		public function get extensions():Array { return _extensions; };
		//上传时的加密文件名
		private var md5_filename:String = "";
		public function get fileName():String { return md5_filename; };
		//后台处理文件地址--->upload.aspx
		private var _path:String = "";
		public function get filePath():String { return _path; };
		public function set filePath(value:String):void { _path = value; };
		//是否预览
		private var _isPreview:Boolean = false;
		public function get isPreview():Boolean { return _isPreview; };
		public function set isPreview(value:Boolean):void { _isPreview = value; };
	}
}